import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/game_subcription_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/games/game_utils/game_utils_controller.dart';
import 'package:flutter_syt/domain/games/subscription_item.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

class SubscriptionPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SubscriptionPageState();
  }
}

class _SubscriptionPageState extends State<SubscriptionPage> {
  List<GameSubscriptionDataItem> allData = [];
  List<GameSubscriptionDataItem> recommendListData = [];
  bool showBottomButton = false;

  NormalTableViewController _normalTableViewController =
      NormalTableViewController();

  @override
  void initState() {
    UserInfo.me.addListener(() {
      _normalTableViewController.reloadData();
    });
    GameUtilsController.managerCont['1'] = _normalTableViewController;
    super.initState();
  }

  Widget emptyRender(BuildContext ctx) {
    if (allData.isNotEmpty) {
      return Container();
    }
    return Container(
      height: 217,
      // color: Colors.red,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(height: 50),
          Text(
            S().No_events_subscribed,
            style: TextStyle(
              color: Colors.black.withOpacity(0.6),
              fontSize: 14,
              // fontWeight: FontWeight.w300,
            ),
          ),
          Container(
            height: 25,
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: ClickUtils.debounce(() async {
              if (!UserInfo.me.isLogin) {
                await RouteManager.push(
                  context,
                  RoutMapping.loginByPwd(),
                );
                _normalTableViewController.reloadData();
                return;
              }
              await RouteManager.push(
                context,
                RoutMapping.SubScriptionManagePage(),
              );
              _normalTableViewController.reloadData();
            }),
            child: Container(
              // width: 220.w,
              height: 36.w,
              padding: EdgeInsets.symmetric(horizontal: 16),
              // margin: ,
              decoration: BoxDecoration(
                  color: Color(0xffF7D749),
                  borderRadius: BorderRadius.circular(8)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.add,
                    size: 13.w,
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  Text(
                    S().Add_events_that_interest_me,
                    style: FontStyles.headerTextStyle_14.copyWith(
                      color: ThemeColor.colorBlack80,
                    ),
                  )
                ],
              ),
            ),
          ),
          SizedBox(height: 50),
          Visibility(
              visible: recommendListData.isNotEmpty,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset('assets/icons/game_recommend_row.png',
                      width: 15, height: 2),
                  SizedBox(width: 12),
                  Text(
                    S.of(context).Recommend,
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontFamily: "PingFang SC",
                    ),
                  ),
                  SizedBox(width: 12),
                  Image.asset('assets/icons/game_recommend_row.png',
                      width: 15, height: 2),
                ],
              ))
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
          color: ThemeColor.bkColorF8F8F8,
          // color: Colors.red,
          child: NormalTableView<SubscriptionItemEntity>(
            controller: _normalTableViewController,
            itemBuilder: (ctx, item) {
              return GestureDetector(
                onTap: ClickUtils.debounce(() {
                  {
                    RouteManager.push(context,
                        RoutMapping.gameDetail(item.data.id, isVideo: false));
                  }
                }),
                child: SubscriptionItem(
                    item.data, item.showDateTitle, item.recommend),
              );
            },
            header: emptyRender,
            getData: (page) async {
              try {
                List<GameSubscriptionDataItem> list = [];
                if (UserInfo.me.isLogin) {
                  list = await API.shared.game.subscribeList(page);
                }
                // 这是显示推荐列表的逻辑
                var isRecommend = false;
                if (page == 1) {
                  allData = [];
                }
                if (page == 1 && list.isEmpty) {
                  isRecommend = true;
                  list = await API.shared.game.recommendSchedule();
                } else {
                  recommendListData = [];
                }
                if (list.length == 0) {
                  if (page == 1 && showBottomButton) {
                    setState(() {
                      showBottomButton = false;
                    });
                  }
                  return [];
                }
                List<SubscriptionItemEntity> entityList = [];
                if (isRecommend) {
                  entityList = list.map((e) {
                    return SubscriptionItemEntity(
                      e,
                      showDateTitle: false,
                      recommend: true,
                      // isRecommend: true,
                    );
                  }).toList();
                  recommendListData = list;
                  allData = [];
                  setState(() {
                    showBottomButton = false;
                  });
                } else {
                  entityList = list.map((e) {
                    bool showDateTitle = false;
                    // 第一条和所有数据的最后一条比较
                    if (list.indexOf(e) == 0) {
                      if (allData.length == 0 || e.date != allData.last.date) {
                        showDateTitle = true;
                      }
                    } else if (e.date != list[list.indexOf(e) - 1].date) {
                      showDateTitle = true;
                    } else {
                      showDateTitle = false;
                    }
                    return SubscriptionItemEntity(
                      e,
                      showDateTitle: showDateTitle,
                      recommend: false,
                      // isRecommend: false,
                    );
                  }).toList();
                  allData.addAll(list);
                  if (showBottomButton == false && allData.length > 0) {
                    setState(() {
                      showBottomButton = true;
                    });
                  }
                }
                return entityList;
              } catch (e) {
                // debugPrintStack();
                if (page == 1 && showBottomButton) {
                  setState(() {
                    showBottomButton = false;
                  });
                }
                return [];
              }
              // return [];
            },
          ),
        ),
        if (showBottomButton)
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              width: double.infinity,
              height: 52,
              padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
              color: Colors.white,
              child: ElevatedButton(
                  child: Text(
                    S().Manage_my_subscriptions,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  onPressed: ClickUtils.debounce(
                    () async {
                      await RouteManager.push(
                        context,
                        RoutMapping.SubScriptionManagePage(),
                      );
                      _normalTableViewController.reloadData();
                    },
                  )),
            ),
          ),
      ],
    );
  }
}
